package com.coocaa.coolink_tvos_mobile_demo.ui.home;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.coocaa.coolink_tvos_mobile_demo.events.MessageEvent;
import com.coocaa.coolink_tvos_mobile_demo.ui.recyclelist.Item;
import com.coocaa.coolink_tvos_mobile_demo.ui.recyclelist.ItemAdapter;
import com.coocaa.obrr_sdk.apiinterface.IWebSocketLink;
import com.coocaa.obrr_sdk.easyapi.ObrrSDKEasyApi;
import com.coocaa.obrr_sdk.easyapi.models.UniqueTunnel;
import com.coocaa.obrr_sdk.easyinterface.IObrrSDKEasy;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class HomeViewModel extends AndroidViewModel implements ItemAdapter.IItemSelectedListener {

    private final MutableLiveData<String> mFilePathText;
    private final MutableLiveData<List<Item>> mSavedListItem;

    private final MutableLiveData<String> mNickNameText;
    private final MutableLiveData<String> mClientIDText;

    private final MutableLiveData<String> mConnectedStateText;

    private List<Item> itemList;
    private Context mContext;

    private String currentNickName;
    private String currentCoolinkID;
    private CustomConnectListener connectListener;

    Handler refreshThreadHandler;
    public HomeViewModel(Application application) {
        super(application);
        mContext = application.getApplicationContext();
        mFilePathText = new MutableLiveData<>();
        mNickNameText = new MutableLiveData<>();
        mClientIDText = new MutableLiveData<>();
        mConnectedStateText = new MutableLiveData<>();

        mSavedListItem = new MutableLiveData<>();
        itemList = new ArrayList<>();
        mSavedListItem.setValue(itemList);

        loadDataFromSP();
        connectListener = new CustomConnectListener();

        HandlerThread handlerThread = new HandlerThread("myHandlerThread");
        handlerThread.start();

// 在 HandlerThread 对象上创建一个 Looper 对象，并通过该 Looper 创建 Handler 对象
        Looper looper = handlerThread.getLooper();
        refreshThreadHandler = new Handler(looper);
// 定义一个 Runnable 对象
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        int type = event.getType();
        if (type == 1){
            // 初始化
            initEasySdkCheckState();
        }else if (type == 2){
            String message = event.getMessage();
            Toast.makeText(getApplication(),message,Toast.LENGTH_LONG).show();
            updateConnectedStateText(message);
        }else if(type == 3){
            String clientID = event.getMessage();
            Item refreshedItem = null;
            for (Item item:itemList) {
                if (item.getClientID().equalsIgnoreCase(clientID)) {
                    refreshedItem = item;
                    refreshedItem.setState(Item.ITEM_STATE.CONNECTED);
                    break;
                }
            }
            updateDataList(itemList);
        }
    }

    public void initEasySdkCheckState(){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                // 每次执行任务的具体逻辑
                for (Item item:itemList) {
                    if(ObrrSDKEasyApi.getInstance().isDeviceConnectReady(item.getClientID())){
                        continue;
                    }
                    ObrrSDKEasyApi.getInstance().queryClientIsOnLineInThread(item.getClientID(),new IWebSocketLink.IQueryClientIDIsOnLineCallBack(){
                        @Override
                        public void onUniqueClientIDOnLine(boolean isSuccess,String uniqueClientID,boolean isOnLine) {
                            if (isSuccess) {
                                Item refreshedItem = null;
                                if (isOnLine) {
                                    //在线
                                    for (Item item:itemList) {
                                        if (item.getClientID().equalsIgnoreCase(uniqueClientID)) {
                                            refreshedItem = item;
                                            refreshedItem.setState(Item.ITEM_STATE.VISIABLE);
                                            break;
                                        }
                                    }

                                }else{
                                    //离线
                                    for (Item item:itemList) {
                                        if (item.getClientID().equalsIgnoreCase(uniqueClientID)) {
                                            refreshedItem = item;
                                            refreshedItem.setState(Item.ITEM_STATE.INVISIABLE);
                                            break;
                                        }
                                    }
                                }
                                updateDataListInThread(itemList);
                            }
                        }
                    });
                }

                // 10s刷新一下设备状态，真实生产环境需要监听服务器推送设备离线消息，不允许这么写。
                refreshThreadHandler.postDelayed(this, 10 * 1000);
            }
        };
        refreshThreadHandler.post(runnable);
    }

    public LiveData<String> getFilePathText() {
        return mFilePathText;
    }

    public LiveData<String> getNickNameText() {
        return mNickNameText;
    }

    public LiveData<String> getClientIDText() {
        return mClientIDText;
    }

    public LiveData<List<Item>> getSavedListIem() {
        return mSavedListItem;
    }

    public LiveData<String> getConnectedStateText(){
        return mConnectedStateText;
    }

    public void updateDataList(List<Item> newDataList) {
        mSavedListItem.setValue(newDataList);
    }

    public void updateDataListInThread(List<Item> newDataList) {
        mSavedListItem.postValue(newDataList);
    }

    public void updateConnectedStateText(String text) {
        mConnectedStateText.setValue(text);
    }

    public void updateFilePathTextView(String text) {
        mFilePathText.setValue(text);
    }

    public void setNickNameText(String text) {
        currentNickName = text;
        Log.d(getClass().getSimpleName(),"setNickNameText = "+text);
    }

    public void setCoolinkIDText(String text){
        currentCoolinkID = text;
        Log.d(getClass().getSimpleName(),"setCoolinkIDText = "+text);
    }

    public void setSaveBtnClicked() {
        if (currentNickName.isEmpty() || currentCoolinkID.isEmpty()){
            return;
        }
        saveToSP();
    }

    public class CustomConnectListener implements IObrrSDKEasy.IConnectorListener{

        @Override
        public void onConnectFailed(UniqueTunnel uniqueTunnel, String s) {
            Log.d(getClass().getSimpleName(),"onConnectFailed" + s);
            String message = uniqueTunnel.getRemoteID() +" had been onConnectFailed!";
            EventBus.getDefault().post(new MessageEvent(2,message));
        }

        @Override
        public void onConnected(UniqueTunnel uniqueTunnel, boolean b) {
            Log.d(getClass().getSimpleName(),"onConnected " + uniqueTunnel.getRemoteID());
            String message = uniqueTunnel.getRemoteID() +" had been onConnected!";
            EventBus.getDefault().post(new MessageEvent(2,message));
        }

        @Override
        public void onReadyToSend(UniqueTunnel uniqueTunnel, boolean b) {
            Log.d(getClass().getSimpleName(),"onReadyToSend " + uniqueTunnel.getRemoteID());
            String message = uniqueTunnel.getRemoteID() +" onReadyToSend!";
            EventBus.getDefault().post(new MessageEvent(2,message));
        }

        @Override
        public void onConnectLinkChanged(UniqueTunnel uniqueTunnel, boolean b) {
            Log.d(getClass().getSimpleName(),"onConnectLinkChanged " + uniqueTunnel.getRemoteID());
            String message = uniqueTunnel.getRemoteID() +" onConnectLinkChanged!";
            EventBus.getDefault().post(new MessageEvent(2,message));
        }

        @Override
        public void onConnectUnStable(UniqueTunnel uniqueTunnel, boolean b) {
            Log.d(getClass().getSimpleName(),"onConnectUnStable " + uniqueTunnel.getRemoteID());
            String message = uniqueTunnel.getRemoteID() +" onConnectUnStable!";
            EventBus.getDefault().post(new MessageEvent(2,message));
        }

        @Override
        public void onPreDisconnect(UniqueTunnel uniqueTunnel, boolean b) {
            Log.d(getClass().getSimpleName(),"onPreDisconnect " + uniqueTunnel.getRemoteID());
            String message = uniqueTunnel.getRemoteID() +" onPreDisconnect!";
            EventBus.getDefault().post(new MessageEvent(2,message));
        }

        @Override
        public void onDisconnected(UniqueTunnel uniqueTunnel, boolean b, String s) {
            Log.d(getClass().getSimpleName(),"onDisconnected " + uniqueTunnel.getRemoteID());
            String message = uniqueTunnel.getRemoteID() +" onDisconnected!";
            EventBus.getDefault().post(new MessageEvent(2,message));
        }

        @Override
        public void onContentReceived(UniqueTunnel uniqueTunnel, boolean b, String s, String s1, String s2) {
            Log.d(getClass().getSimpleName(),"onContentReceived " + uniqueTunnel.getRemoteID());
            String message = uniqueTunnel.getRemoteID() +" onContentReceived!";
            EventBus.getDefault().post(new MessageEvent(2,message));
        }

        @Override
        public void onSameRemoteIDConnectKickOff(UniqueTunnel uniqueTunnel) {

        }
    }

    public void setConnectBtnClicked(){
        if (currentNickName.isEmpty() || currentCoolinkID.isEmpty()){
            return;
        }
        if(ObrrSDKEasyApi.getInstance().isDeviceConnectReady(currentCoolinkID)) {
            Toast.makeText(getApplication(),currentCoolinkID +" had been Connected!",Toast.LENGTH_LONG).show();
        }else{
            IObrrSDKEasy.ERtmTunnelState result = ObrrSDKEasyApi.getInstance().connectPeerAsControlling(currentCoolinkID,connectListener);
            switch (result){
                case TUNNEL_ALREADY_EXISTED:
                    break;
                case TUNNEL_CONNECT_FAILED:
                    break;
                case TUNNEL_CONNECT_SUCCESS:
                    break;
            }
        }
    }

    void saveToSP(){
// 存储列表数据
        for (Item eachItem: itemList){
            if (eachItem.getName().equalsIgnoreCase(currentNickName)){
                Toast.makeText(mContext,"已经有该名称的设备",Toast.LENGTH_LONG).show();
                return;
            }
        }
        for (Item eachItem: itemList){
            if (eachItem.getClientID().equalsIgnoreCase(currentCoolinkID)){
                Toast.makeText(mContext,"已经有该唯一ID的设备",Toast.LENGTH_LONG).show();
                return;
            }
        }

        itemList.add(new Item(currentNickName,currentCoolinkID));
        SharedPreferences sharedPreferences = mContext.getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
        List<JSONObject> dataList = new ArrayList<>();
        for (int i = 0; i < itemList.size(); i++) {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("name", itemList.get(i).getName());
                jsonObject.put("id", itemList.get(i).getClientID()); // 将id转换为字符串类型
            } catch (JSONException e) {
                e.printStackTrace();
            }
            dataList.add(jsonObject);
        }
        JSONArray jsonArray = new JSONArray(dataList);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("dataList", jsonArray.toString());
        editor.apply();

        updateDataList(itemList);
    }

    void forceSaveToSp(){
        SharedPreferences sharedPreferences = mContext.getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
        List<JSONObject> dataList = new ArrayList<>();
        for (int i = 0; i < itemList.size(); i++) {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("name", itemList.get(i).getName());
                jsonObject.put("id", itemList.get(i).getClientID()); // 将id转换为字符串类型
            } catch (JSONException e) {
                e.printStackTrace();
            }
            dataList.add(jsonObject);
        }
        JSONArray jsonArray = new JSONArray(dataList);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("dataList", jsonArray.toString());
        editor.apply();
    }

    public void loadDataFromSP(){
        // 获取SharedPreferences对象
        SharedPreferences sharedPreferences = mContext.getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
// 读取列表数据
        // 使用SharedPreferences进行读取
        // 读取列表数据
        String jsonString = sharedPreferences.getString("dataList", null);
        if (jsonString != null) {
            try {
                JSONArray jsonArray = new JSONArray(jsonString);
                List<JSONObject> dataList = new ArrayList<>();
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    dataList.add(jsonObject);
                }
                for (JSONObject jsonObject : dataList) {
                    String name = jsonObject.getString("name");
                    String id = jsonObject.getString("id"); // 将id转换为字符串类型
                    Log.d(getClass().getSimpleName(), "name: " + name + ", id: " + id);
                    itemList.add(new Item(name,id));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void onItemRadioButtonSelected(Item item) {
        if (item!=null) {
            mNickNameText.setValue(item.getName());
            mClientIDText.setValue(item.getClientID());
        }
    }

    @Override
    public void onItemDeleted(Item item) {
        // 删除了这个item
        Item deleteItem = null;
        for (Item eachItem: itemList){
            if (eachItem.getName().equalsIgnoreCase(item.getName())){
                deleteItem = eachItem;
                itemList.remove(eachItem);
                break;
            }
        }
        forceSaveToSp();
        updateDataList(itemList);

        if (deleteItem!=null && ObrrSDKEasyApi.getInstance().isDeviceConnectReady(deleteItem.getClientID())){
            ObrrSDKEasyApi.getInstance().disconnectP2P(deleteItem.getClientID());
        }
    }
}